///| 转换
/// 字符串转整数
/// 字符串转浮点数
/// 字符串转布尔值
pub(all) struct Convert {}

///| 字符串转整数
pub fn Convert::string_to_int(str : String) -> Int? {
  let trimmed = str.trim(" \t\n\r")
  if trimmed.is_empty() {
    return None
  }
  let mut result = 0
  let mut index = 0
  let mut is_negative = false

  // Handle sign
  if trimmed[0] == '-' {
    is_negative = true
    index = 1
  } else if trimmed[0] == '+' {
    index = 1
  }

  // Check if there are digits after sign
  if index >= trimmed.length() {
    return None
  }

  // Parse digits
  while index < trimmed.length() {
    let char = trimmed[index]
    if char >= '0' && char <= '9' {
      let digit = char - '0'.to_int()
      result = result * 10 + digit
      index = index + 1
    } else {
      return None // Invalid character
    }
  }
  if is_negative {
    Some(-result)
  } else {
    Some(result)
  }
}

///| 字符串转整数，当字符串为浮点数时，取整数部分
pub fn Convert::string_to_int_truncate(str : String) -> Int? {
  let trimmed = str.trim(" \t\n\r")
  if trimmed.is_empty() {
    return None
  }
  let mut result = 0
  let mut index = 0
  let mut is_negative = false

  // Handle sign
  if trimmed[0] == '-' {
    is_negative = true
    index = 1
  } else if trimmed[0] == '+' {
    index = 1
  }

  // Check if there are digits after sign
  if index >= trimmed.length() {
    return None
  }

  // Parse digits until decimal point or end of string
  while index < trimmed.length() {
    let char = trimmed[index]
    if char >= '0' && char <= '9' {
      let digit = char - '0'.to_int()
      result = result * 10 + digit
      index = index + 1
    } else if char == '.' {
      // Found decimal point, stop parsing (truncate decimal part)
      break
    } else {
      return None // Invalid character
    }
  }
  if is_negative {
    return Some(-result)
  }
  Some(result)
}

///| 字符串转浮点数
pub fn Convert::string_to_double(str : String) -> Double? {
  let trimmed = str.trim(" \t\n\r")
  if trimmed.is_empty() {
    return None
  }
  
  let mut index = 0
  let mut is_negative = false
  let mut mantissa = 0.0
  let mut has_decimal = false
  let mut decimal_places = 0.0
  let mut has_exponent = false
  let mut exponent = 0
  let mut exponent_negative = false
  
  // 处理尾数的符号
  if index < trimmed.length() && trimmed[index] == '-' {
    is_negative = true
    index = index + 1
  } else if index < trimmed.length() && trimmed[index] == '+' {
    index = index + 1
  }
  
  // 检查符号后是否有数字
  if index >= trimmed.length() {
    return None
  }
  
  // 解析尾数（整数部分和小数部分）
  let mut has_digits = false
  while index < trimmed.length() {
    let char = trimmed[index]
    if char >= '0' && char <= '9' {
      has_digits = true
      let digit = (char - '0').to_double()
      if has_decimal {
        decimal_places = decimal_places + 1.0
        mantissa = mantissa + digit / 10.0.pow(decimal_places)
      } else {
        mantissa = mantissa * 10.0 + digit
      }
      index = index + 1
    } else if char == '.' && not(has_decimal) {
      has_decimal = true
      index = index + 1
    } else if char == 'e' || char == 'E' {
      has_exponent = true
      index = index + 1
      break
    } else {
      return None // 无效字符
    }
  }
  
  // 尾数必须至少包含一个数字
  if not(has_digits) {
    return None
  }
  
  // 如果存在指数部分，则解析指数
  if has_exponent {
    // 处理指数的符号
    if index < trimmed.length() && trimmed[index] == '-' {
      exponent_negative = true
      index = index + 1
    } else if index < trimmed.length() && trimmed[index] == '+' {
      index = index + 1
    }
    
    // 指数必须包含数字
    if index >= trimmed.length() {
      return None
    }
    
    let mut has_exp_digits = false
    while index < trimmed.length() {
      let char = trimmed[index]
      if char >= '0' && char <= '9' {
        has_exp_digits = true
        let digit = char - '0'.to_int()
        exponent = exponent * 10 + digit
        index = index + 1
      } else {
        return None // 指数中包含无效字符
      }
    }
    
    // 指数必须至少包含一个数字
    if not(has_exp_digits) {
      return None
    }
  }
  
  // 应用符号
  if is_negative {
    mantissa = -mantissa
  }
  if exponent_negative {
    exponent = -exponent
  }
  
  // 应用指数
  let result = if has_exponent {
    mantissa * 10.0.pow(exponent.to_double())
  } else {
    mantissa
  }
  
  Some(result)
}

///| 字符串转布尔值
pub fn Convert::string_to_bool(str : String) -> Bool? {
  let trimmed = str.trim(" \t\n\r").to_lower()
  if trimmed.is_empty() {
    return None
  }
  if trimmed == "true" {
    return Some(true)
  } else if trimmed == "false" {
    return Some(false)
  } else {
    return None
  }
}

///| 整数转字符串
pub fn Convert::int_to_string(value : Int) -> String {
  value.to_string()
}

///| 浮点数转字符串
pub fn Convert::double_to_string(value : Double) -> String {
  value.to_string()
}

///| 布尔值转字符串
pub fn Convert::bool_to_string(value : Bool) -> String {
  if value {
    "true"
  } else {
    "false"
  }
}

///| 整数转浮点数
pub fn Convert::int_to_double(value : Int) -> Double {
  value.to_double()
}

///| 浮点数转整数（截断小数部分）
pub fn Convert::double_to_int(value : Double) -> Int {
  value.to_int()
}

///| 浮点数转整数（四舍五入）
pub fn Convert::double_to_int_round(value : Double) -> Int {
  if value >= 0.0 {
    (value + 0.5).to_int()
  } else {
    (value - 0.5).to_int()
  }
}

///| 字符转整数（ASCII码值）
pub fn Convert::char_to_int(char : Char) -> Int {
  char.to_int()
}

///| 整数转字符（ASCII码值）
pub fn Convert::int_to_char(value : Int) -> Char? {
  if value >= 0 && value <= 127 {
    value.to_char()
  } else {
    None
  }
}

///| 字符串转字符数组
pub fn Convert::string_to_chars(str : String) -> Array[Char] {
  let chars = []
  for i = 0; i < str.length(); i = i + 1 {
    let char_code = str.charcode_at(i)
    match char_code.to_char() {
      Some(char) => chars.push(char)
      None => continue
    }
  }
  chars
}

///| 字符数组转字符串
pub fn Convert::chars_to_string(chars : Array[Char]) -> String {
  let mut result = ""
  for char in chars {
    result = result + char.to_string()
  }
  result
}

///| 十进制整数转十六进制字符串
pub fn Convert::int_to_hex(value : Int) -> String {
  if value == 0 {
    return "0"
  }
  
  let mut num = if value < 0 { -value } else { value }
  let mut result = ""
  let hex_chars = "0123456789ABCDEF"
  
  while num > 0 {
    let remainder = num % 16
    let char_code = hex_chars.charcode_at(remainder)
    match char_code.to_char() {
      Some(char) => result = char.to_string() + result
      None => continue
    }
    num = num / 16
  }
  
  if value < 0 {
    "-" + result
  } else {
    result
  }
}

///| 十六进制字符串转十进制整数
pub fn Convert::hex_to_int(hex_str : String) -> Int? {
  let trimmed = hex_str.trim(" \t\n\r")
  if trimmed.is_empty() {
    return None
  }
  
  let mut index = 0
  let mut is_negative = false
  
  // 处理符号
  if trimmed[0] == '-' {
    is_negative = true
    index = 1
  } else if trimmed[0] == '+' {
    index = 1
  }
  
  // 跳过可选的 "0x" 或 "0X" 前缀
  if index + 1 < trimmed.length() && trimmed[index] == '0' && 
     (trimmed[index + 1] == 'x' || trimmed[index + 1] == 'X') {
    index = index + 2
  }
  
  if index >= trimmed.length() {
    return None
  }
  
  let mut result = 0
  while index < trimmed.length() {
    let char = trimmed[index]
    let digit = if char >= '0' && char <= '9' {
      char - '0'.to_int()
    } else if char >= 'A' && char <= 'F' {
      char - 'A'.to_int() + 10
    } else if char >= 'a' && char <= 'f' {
      char - 'a'.to_int() + 10
    } else {
      return None // 无效字符
    }
    
    result = result * 16 + digit
    index = index + 1
  }
  
  if is_negative {
    Some(-result)
  } else {
    Some(result)
  }
}

///| 十进制整数转二进制字符串
pub fn Convert::int_to_binary(value : Int) -> String {
  if value == 0 {
    return "0"
  }
  
  let mut num = if value < 0 { -value } else { value }
  let mut result = ""
  
  while num > 0 {
    let remainder = num % 2
    result = remainder.to_string() + result
    num = num / 2
  }
  
  if value < 0 {
    "-" + result
  } else {
    result
  }
}

///| 二进制字符串转十进制整数
pub fn Convert::binary_to_int(binary_str : String) -> Int? {
  let trimmed = binary_str.trim(" \t\n\r")
  if trimmed.is_empty() {
    return None
  }
  
  let mut index = 0
  let mut is_negative = false
  
  // 处理符号
  if trimmed[0] == '-' {
    is_negative = true
    index = 1
  } else if trimmed[0] == '+' {
    index = 1
  }
  
  // 跳过可选的 "0b" 或 "0B" 前缀
  if index + 1 < trimmed.length() && trimmed[index] == '0' && 
     (trimmed[index + 1] == 'b' || trimmed[index + 1] == 'B') {
    index = index + 2
  }
  
  if index >= trimmed.length() {
    return None
  }
  
  let mut result = 0
  while index < trimmed.length() {
    let char = trimmed[index]
    if char == '0' {
      result = result * 2
    } else if char == '1' {
      result = result * 2 + 1
    } else {
      return None // 无效字符
    }
    index = index + 1
  }
  
  if is_negative {
    Some(-result)
  } else {
    Some(result)
  }
}
